<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        let list = [
            {
                id: 1,
                pid: 0,
                name: "部门一",
                type: 1,
            },
            {
                id: 2,
                pid: 0,
                name: "部门一",
                type: 1,
            },
            {
                id: 3,
                pid: 0,
                name: "部门一",
                type: 1,
            },
            {
                id: 4,
                pid: 0,
                name: "部门一",
                type: 1,
            },
            {
                id: 5,
                pid: 0,
                name: "部门一",
                type: 1,
            },
        ]
        // 递归
        // let tree = [
        //     {
        //         "id": 1,
        //         "pid": 0,
        //         "name": "部门一",
        //         "type": 1,
        //         "children": [
        //             {
        //                 "id": 4,
        //                 "pid": 1,
        //                 "name": "子部门一",
        //                 "type": 1,
        //                 "children": [
        //                     {
        //                         "id": 7,
        //                         "pid": 4,
        //                         "name": "子部门四",
        //                         "type": 1,
        //                         "children": []
        //                     },
        //                     {
        //                         "id": 11,
        //                         "pid": 4,
        //                         "name": "人员四",
        //                         "type": 1,
        //                         "children": []
        //                     }
        //                 ]
        //             }
        //         ]
        //     }
        // ];
        const tree = list.reduce((acc, cur) => {
                cur.children = []
                acc[cur.id] = cur
                const parent = acc[cur.pid]
                parent ? parent.children.push(cur) : acc[0].children.push(cur)
                return acc
            }, { [0]: { children: [] } })[0].children
    </script>
</body>

</html>
